<script setup lang="ts">
import { onMounted, ref, watch } from 'vue';
import { fetchDashboardsLineChart } from '@/service/api/business/products';
import { useAppStore } from '@/store/modules/app';
import { useEcharts } from '@/hooks/common/echarts';
import { $t } from '@/locales';

defineOptions({
  name: 'LineChart'
});

const appStore = useAppStore();
const lineChartData = ref<Api.Business.DashboardLineChart[]>([]);

// 获取折线图数据
const fetchLineChartData = async () => {
  try {
    const res = await fetchDashboardsLineChart();
    // 根据你的返回数据结构，data.todayOrdersList 是数组
    lineChartData.value = res.data.todayOrdersList || [];
    updateChartData();
  } catch (error) {
    console.error('获取折线图数据失败:', error);
  }
};

const { domRef, updateOptions } = useEcharts(() => ({
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'cross',
      label: {
        backgroundColor: '#6a7985'
      }
    }
  },
  legend: {
    data: [$t('page.home.downloadCount')] // 只显示一个图例
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: [] as string[]
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      color: '#8e9dff',
      name: $t('page.home.downloadCount'),
      type: 'line',
      smooth: true,
      areaStyle: {
        color: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            {
              offset: 0.25,
              color: '#8e9dff'
            },
            {
              offset: 1,
              color: '#fff'
            }
          ]
        }
      },
      emphasis: {
        focus: 'series'
      },
      data: [] as number[]
    }
  ]
}));

// 更新图表数据
function updateChartData() {
  if (!lineChartData.value || lineChartData.value.length === 0) {
    return;
  }

  // 提取日期和数量数据
  const dates = lineChartData.value.map(item => item.date);
  const counts = lineChartData.value.map(item => item.count);

  updateOptions(opts => {
    opts.xAxis.data = dates;
    opts.series[0].data = counts;
    return opts;
  });
}

function updateLocale() {
  updateOptions((opts, factory) => {
    const originOpts = factory();

    opts.legend.data = originOpts.legend.data;
    opts.series[0].name = originOpts.series[0].name;

    return opts;
  });
}

// 初始化
onMounted(() => {
  fetchLineChartData();
});

watch(
  () => appStore.locale,
  () => {
    updateLocale();
  }
);

// 监听数据变化，重新渲染图表
watch(lineChartData, () => {
  updateChartData();
}, { deep: true });
</script>

<template>
  <NCard :bordered="false" class="card-wrapper">
    <div ref="domRef" class="h-360px overflow-hidden"></div>
  </NCard>
</template>

<style scoped></style>
